package com.xmqian.app.project.ui.main

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.widget.LinearLayout
import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.coszero.common.config.user.UserManager
import com.coszero.ui.dialog.ToastUtils
import com.coszero.utils.app.AppManager
import com.coszero.utils.app.AppUtils
import com.coszero.utils.base.BaseTabViewPagerAdapter
import com.coszero.utils.utils.LogX
import com.example.xmqian.R
import com.example.xmqian.databinding.ActivityMainBottomTabBinding
import com.xmqian.app.project.common.base.BaseMyActivity
import com.xmqian.app.project.common.testdata.TestData
import com.xmqian.app.project.event.LoginEvent
import com.xmqian.app.project.model.MainBottomMenuModel
import com.xmqian.app.project.ui.main.fragment.MainPage1Fragment
import com.xmqian.app.project.ui.user.activity.LoginActivity
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Desc： 拥有底部切换菜单的主页
 *
 *
 * Author： xmqian
 * Email:xmqian93@163.com
 * Date: 2019/9/19 17:26
 */
class MainBottomTabActivity : BaseMyActivity() {
    private var lastPressBackKeyTime: Long = 0
    var mVpFragment: ViewPager? = null
    var mRgTab: RadioGroup? = null
    private val mFragments: MutableList<Fragment> = ArrayList()
    private val tabMenus: MutableList<MainBottomMenuModel> = ArrayList()
    private var lastCheckId = 0
    private var binding: ActivityMainBottomTabBinding? = null

    override fun getLayoutView(): LinearLayout {
        binding = ActivityMainBottomTabBinding.inflate(layoutInflater)
        return binding!!.root
    }

    override fun initView() {
        mVpFragment = binding!!.vpFragment
        mRgTab = binding!!.rgTab
        UserManager.getInstance().saveLoginData("妖精尾巴毛", "321", TestData.headImage)
        UserManager.getInstance().initLoginData()
        mFragments.add(
            MainPage1Fragment.Companion.newInstance(
                AppUtils.getString(
                    mActivity,
                    R.string.app_name
                )
            )
        )
        mFragments.add(MainPage1Fragment.Companion.newInstance("页面一"))
        mFragments.add(MainPage1Fragment.Companion.newInstance("页面二"))
        mFragments.add(MainPage1Fragment.Companion.newInstance("页面三"))
        mVpFragment.setAdapter(BaseTabViewPagerAdapter(supportFragmentManager, mFragments))
        mVpFragment.setOffscreenPageLimit(mFragments.size)
        initBottomTabs()
    }

    override fun initData() {
    }

    @SuppressLint("NonConstantResourceId")
    private fun initBottomTabs() {
        tabMenus.add(
            MainBottomMenuModel(
                R.drawable.sl_main_tab1,
                AppUtils.getString(mActivity, R.string.app_name),
                R.id.rb_0
            )
        )
        tabMenus.add(MainBottomMenuModel(R.drawable.sl_main_tab1, "页面一", R.id.rb_1))
        tabMenus.add(MainBottomMenuModel(R.drawable.sl_main_tab1, "页面二", R.id.rb_2))
        tabMenus.add(MainBottomMenuModel(R.drawable.sl_main_tab1, "页面三", R.id.rb_3))
        for (i in tabMenus.indices) {
            val inflate = layoutInflater.inflate(R.layout.view_radiobutton, null) as RadioButton
            val layoutParams =
                RadioGroup.LayoutParams(0, RadioGroup.LayoutParams.WRAP_CONTENT, 1.0f)
            inflate.layoutParams = layoutParams
            inflate.id = tabMenus[i].viewId
            AppUtils.setTopIcon(resources.getDrawable(tabMenus[i].topDrawable), inflate)
            inflate.text = tabMenus[i].tabName
            mRgTab!!.addView(inflate)
        }
        mRgTab!!.setOnCheckedChangeListener { group: RadioGroup?, checkedId: Int ->
            if (checkedId == R.id.rb_0) {
                changeFragment(R.id.rb_0, 0)
            } else if (checkedId == R.id.rb_1) {
                changeFragment(R.id.rb_1, 1)
            } else if (checkedId == R.id.rb_2) {
                changeFragment(R.id.rb_2, 2)
            } else if (checkedId == R.id.rb_3) {
                if (!checkLogin()) {
                    mRgTab!!.check(lastCheckId)
                    return@setOnCheckedChangeListener
                }
                changeFragment(R.id.rb_3, 3)
            }
        }
        //默认选中第一个页面
        mRgTab!!.check(R.id.rb_0)
        lastCheckId = R.id.rb_0
    }

    /**
     * @param lastCheckId 最后选择的id
     * @param i 选择的位置
     */
    private fun changeFragment(lastCheckId: Int, i: Int) {
        this.lastCheckId = lastCheckId
        mVpFragment!!.setCurrentItem(i, false)
    }

    private fun checkLogin(): Boolean {
        if (!UserManager.getInstance().isLogin) {
            ToastUtils.showMsg("请先登录")
            LoginActivity.Companion.startActivity(this)
            return false
        }
        return true
    }

    override fun onBackPressed() {
        if (System.currentTimeMillis() - lastPressBackKeyTime < DELAY_TIME) {
            super.onBackPressed()
        } else {
            lastPressBackKeyTime = System.currentTimeMillis()
            ToastUtils.showLongMsg(resources.getString(R.string.toast_press_again_exit_app))
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLoginEvent(event: LoginEvent) {
        if (event.isLogin) {
            LogX.i("### 登录成功")
            ToastUtils.showMsg("登录成功")
        } else {
            UserManager.getInstance().clearLoginData()
            LogX.i("### 退出登录成功")
            AppManager.getAppManager().finishAllActivity()
        }
    }

    companion object {
        private const val DELAY_TIME: Long = 1500 //退出间隔时间

        /**
         * 单例开启页面，如果堆栈中有，则从底部将页面拉上次，上面的页面全部销毁
         */
        fun startTask(context: Context) {
            val intent = Intent()
            intent.setClass(context, MainBottomTabActivity::class.java)
            intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            context.startActivity(intent)
        }
    }
}
